var commonCityData = require('../../utils/city.js')
var md5 = require("../../utils/md5.js");
var app = getApp();
Page({
  data: {
    provinces: [],
    citys: [],
    defaultProvinceCode: 2,
    defaultCityCode: 3,
    defaultCountyCode: 16,
    defaultAddressCode: '057750',
    districts: [],
    selProvince: '请选择',
    selCity: '请选择',
    selDistrict: '请选择',
    selProvinceIndex: 0,
    selCityIndex: 0,
    selDistrictIndex: 0,
    addressInfo: {},
  },
  bindCancel: function() {
    wx.navigateBack({})
  },
  bindSave: function(e) {
    var that = this;
    wx.showLoading();
    var contact_name = e.detail.value.contact_name;
    var contact_tel = e.detail.value.contact_tel;
    var contact_address = e.detail.value.contact_address;
    var contact_menpai = e.detail.value.contact_menpai;
    var sex = e.detail.value.sex;
    if (contact_name == "") {
      wx.showModal({
        title: '提示',
        content: '请填写联系人',
        showCancel: false
      })
      wx.hideLoading();
      return
    }
    if (sex == "") {
      wx.showModal({
        title: '提示',
        content: '请选择性别',
        showCancel: false
      })
      wx.hideLoading();
      return
    }
    if (contact_tel == "") {
      wx.showModal({
        title: '提示',
        content: '请填写手机号',
        showCancel: false
      })
      wx.hideLoading();
      return
    }
    if (contact_address == "") {
      wx.showModal({
        title: '提示',
        content: '请填写收货地址',
        showCancel: false
      })
      wx.hideLoading();
      return
    }
    if (contact_menpai == "") {
      wx.showModal({
        title: '提示',
        content: '请填写门牌号',
        showCancel: false
      })
      wx.hideLoading();
      return
    }
    if (sex == '1') {
      contact_sex = "先生";
    } else {
      contact_sex = "女士";
    }
    if (this.data.addressType == 'create') {
      var contact_address = contact_address;
      var contact_address_jingwei = this.data.addressInfo && this.data.addressInfo.contact_address_jingwei || "";
      var contact_menpai = contact_menpai;
      var contact_name = contact_name;
      var contact_sex = contact_sex;
      var contact_tel = contact_tel;
      var is_moren = 0;
      var open_id = app.globalData.openId;
      var service = 'Order.AddNewAddress';
      var user_id = app.globalData.userId;
      var sign = md5.md5(contact_address + contact_address_jingwei + contact_menpai + contact_name + contact_sex + contact_tel + is_moren + open_id + service + user_id);
      wx.request({
        url: app.globalData.serviceUrl + 'Order.AddNewAddress',
        header: {
          'Content-Type': 'json'
        },
        data: {
          contact_address: contact_address,
          contact_address_jingwei: contact_address_jingwei,
          contact_menpai: contact_menpai,
          contact_name: contact_name,
          contact_sex: contact_sex,
          contact_tel: contact_tel,
          is_moren: is_moren,
          open_id: open_id,
          user_id: user_id,
          sign: sign
        },
        success: function(res) {
          var result = res.data.data;
          if (result.code != 0) {
            // 登录错误 
            wx.hideLoading();
            wx.showModal({
              title: '失败',
              content: res.data.msg,
              showCancel: false
            })
            return;
          }
          var address = {
            "contact_address": contact_address,
            "contact_name": contact_name,
            "contact_sex": contact_sex,
            "contact_tel": contact_tel,
            "contact_menpai": contact_menpai,
            "contact_address_jingwei": contact_address_jingwei
          }

          wx.setStorageSync('addressSelectInfo', address);
          wx.navigateBack({})
        },
        complete: function(res) {
          console.log(res);
        },
      })
    } else {
      var address_id = that.data.addressInfo.address_id;
      var contact_address = contact_address;
      var contact_address_jingwei = this.data.addressInfo.contact_address_jingwei || "";
      var contact_menpai = contact_menpai;
      var contact_name = contact_name;
      var contact_sex = contact_sex;
      var contact_tel = contact_tel;
      var is_moren = 0;
      var open_id = app.globalData.openId;
      var service = 'Order.EditNewAddress';
      var user_id = app.globalData.userId;
      var sign = md5.md5(address_id + contact_address + contact_address_jingwei + contact_menpai + contact_name + contact_sex + contact_tel + is_moren + open_id + service + user_id);
      wx.request({
        url: app.globalData.serviceUrl + 'Order.EditNewAddress',
        header: {
          'Content-Type': 'json'
        },
        data: {
          address_id: address_id,
          contact_address: contact_address,
          contact_address_jingwei: contact_address_jingwei,
          contact_menpai: contact_menpai,
          contact_name: contact_name,
          contact_sex: contact_sex,
          contact_tel: contact_tel,
          is_moren: is_moren,
          open_id: open_id,
          user_id: user_id,
          sign: sign
        },
        success: function(res) {
          var result = res.data.data;
          if (result.code != 0) {

            wx.hideLoading();
            wx.showModal({
              title: '失败',
              content: res.data.msg,
              showCancel: false
            })
            return;
          }
          var address = {
            "address_id": address_id,
            "contact_address": contact_address,
            "contact_name": contact_name,
            "contact_sex": contact_sex,
            "contact_tel": contact_tel,
            "contact_menpai": contact_menpai,
            "contact_address_jingwei": contact_address_jingwei
          }
          wx.setStorageSync('addressSelectInfo', address);
          wx.navigateBack({})
        },
        complete: function(res) {
          console.log(res);
        },
      })
    }
  },
  initCityData: function(level, obj) {
    if (level == 1) {
      var pinkArray = [];
      for (var i = 0; i < commonCityData.cityData.length; i++) {
        pinkArray.push(commonCityData.cityData[i].name);
      }
      this.setData({
        provinces: pinkArray
      });
    } else if (level == 2) {
      var pinkArray = [];
      var dataArray = obj.cityList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        citys: pinkArray
      });
    } else if (level == 3) {
      var pinkArray = [];
      var dataArray = obj.districtList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        districts: pinkArray
      });
    }

  },
  bindPickerProvinceChange: function(event) {
    var selIterm = commonCityData.cityData[event.detail.value];
    this.setData({
      selProvince: selIterm.name,
      selProvinceIndex: event.detail.value,
      selCity: '请选择',
      selCityIndex: 0,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.initCityData(2, selIterm)
  },
  bindPickerCityChange: function(event) {
    var selIterm = commonCityData.cityData[this.data.selProvinceIndex].cityList[event.detail.value];
    this.setData({
      selCity: selIterm.name,
      selCityIndex: event.detail.value,
      selDistrict: '请选择',
      selDistrictIndex: 0
    })
    this.initCityData(3, selIterm)
  },
  bindPickerChange: function(event) {
    var selIterm = commonCityData.cityData[this.data.selProvinceIndex].cityList[this.data.selCityIndex].districtList[event.detail.value];
    if (selIterm && selIterm.name && event.detail.value) {
      this.setData({
        selDistrict: selIterm.name,
        selDistrictIndex: event.detail.value
      })
    }
  },
  onLoad: function(e) {
    var that = this;
    this.initCityData(1);
    var id = e.id;
    if (id) {
      // 初始化原数据
      var addressInfo = wx.getStorageSync('addressInfo');
      if (addressInfo.contact_sex == '先生') {
        addressInfo.contact_sexN = "1";
      }
      if (addressInfo.contact_sex == '女士') {
        addressInfo.contact_sexN = "2";
      }
      that.setData({
        addressInfo: addressInfo,
        addressType: 'edit',
      });
      //that.setDBSaveAddressId(res.data.data);
    } else {
      that.setData({
        addressType: 'create',
      });
    }
  },
  setDBSaveAddressId: function(data) {
    var retSelIdx = 0;
    for (var i = 0; i < commonCityData.cityData.length; i++) {
      if (data.provinceId == commonCityData.cityData[i].id) {
        this.data.selProvinceIndex = i;
        for (var j = 0; j < commonCityData.cityData[i].cityList.length; j++) {
          if (data.cityId == commonCityData.cityData[i].cityList[j].id) {
            this.data.selCityIndex = j;
            for (var k = 0; k < commonCityData.cityData[i].cityList[j].districtList.length; k++) {
              if (data.districtId == commonCityData.cityData[i].cityList[j].districtList[k].id) {
                this.data.selDistrictIndex = k;
              }
            }
          }
        }
      }
    }
  },
  readFromWx: function() {
    let that = this;
    wx.chooseAddress({
      success: function(res) {
        let provinceName = res.provinceName;
        let cityName = res.cityName;
        let diatrictName = res.countyName;
        let retSelIdx = 0;
        console.log(res)
        // for (var i = 0; i < commonCityData.cityData.length; i++) {
        //   if (provinceName == commonCityData.cityData[i].name) {
        //     let eventJ = {
        //       detail: {
        //         value: i
        //       }
        //     };
        //     that.bindPickerProvinceChange(eventJ);
        //     that.data.selProvinceIndex = i;
        //     for (var j = 0; j < commonCityData.cityData[i].cityList.length; j++) {
        //       if (cityName == commonCityData.cityData[i].cityList[j].name) {
        //         //that.data.selCityIndex = j;
        //         eventJ = {
        //           detail: {
        //             value: j
        //           }
        //         };
        //         that.bindPickerCityChange(eventJ);
        //         for (var k = 0; k < commonCityData.cityData[i].cityList[j].districtList.length; k++) {
        //           if (diatrictName == commonCityData.cityData[i].cityList[j].districtList[k].name) {
        //             //that.data.selDistrictIndex = k;
        //             eventJ = {
        //               detail: {
        //                 value: k
        //               }
        //             };
        //             that.bindPickerChange(eventJ);
        //           }
        //         }
        //       }
        //     }
        //   }
        // }
        
        that.setData({
          wxaddress: res,
        });
      }
    })
  },
  getLocation: function() { //缺少未授权的处理
    var that = this;
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            success: function(res) {
              if (res.cancel) {
                console.info("授权失败返回数据");
              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function(data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      });
                      that.getLocationDesc();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          that.getLocationDesc();
        }
      },
      complete: function(res) {
        console.log(res);
      },
    })
  },

  onchange_contact_name: function(event) {
    this.data.addressInfo.contact_name = event.detail.value;
  },

  onchange_contact_sex: function(event) {
    if (value == '1') { //先生
      this.data.addressInfo.contact_sex = "先生";
      this.data.addressInfo.contact_sexN = event.detail.value;
    } else { //女士
      this.data.addressInfo.contact_sex = "女士";
      this.data.addressInfo.contact_sexN = event.detail.value;
    }
  },

  onchange_contact_tel: function(event) {
    this.data.addressInfo.contact_tel = event.detail.value;
  },

  onchange_contact_address: function(event) {
    this.data.addressInfo.contact_address = event.detail.value;
  },

  onchange_contact_menpai: function(event) {
    this.data.addressInfo.contact_menpai = event.detail.value;
  },

  getLocationDesc: function() {
    var that = this;
    if (that.data.addressInfo && that.data.addressInfo.contact_address_jingwei) {
      wx.chooseLocation({
        latitude: parseFloat(that.data.addressInfo.contact_address_jingwei.split(',')[1]), // 纬度，范围为-90~90，负数表示南纬
        longitude: parseFloat(that.data.addressInfo.contact_address_jingwei.split(',')[0]), // 经度，范围为-180~180，负数表示西经
        scale: 18, // 缩放比例
        success: function(res) {
          if (that.data.addressInfo) {
            var addressInfo = that.data.addressInfo;
          } else {
            var addressInfo = {};
          }
          addressInfo.contact_address_jingwei = res.latitude + ',' + res.longitude;
          addressInfo.contact_address = res.address || "";
          that.setData({
            addressInfo: addressInfo,
          })
        },
        complete: function(res) {
          console.log(res);
        },
      })
    } else {
      wx.getLocation({
        type: 'gcj02',
        success: function(res) {
          wx.chooseLocation({
            latitude: 20, // 纬度，范围为-90~90，负数表示南纬
            longitude: 120, // 经度，范围为-180~180，负数表示西经
            scale: 18, // 缩放比例
            success: function(res) {
              if (that.data.addressInfo) {
                var addressInfo = that.data.addressInfo;
              } else {
                var addressInfo = {};
              }
              addressInfo.contact_address_jingwei = res.latitude + ',' + res.longitude;
              addressInfo.contact_address = res.address || "";
              that.setData({
                addressInfo: addressInfo,
              })
            },
            complete: function(res) {
              console.log(res);
            },
          })
        },
        complete: function(res) {
          console.log(res);
        },
      })
    }
  },

})